from dao.picture import PictureDao
from dao.category import CategoryDao
from dao.advertisement import AdvertisementDao
from service.picture import PictureService

import shutil    
import os

class AdvertisementService():
    def __init__(self):
        self.ad_dao = AdvertisementDao()
        
        
    def get_all_infos(self):
        return self.get_infos()
    
    def get_infos(self, query={}):
        picture_dao = PictureDao()
        category_dao = CategoryDao()
        
        ads = self.ad_dao.find(query)
        infos = []
        for ad in ads:
            category = category_dao.find_one({'_id':ad.category._id})
            ItemDaoClass = self.ad_dao.items[category.name][1]
            dao = ItemDaoClass()
            item = dao.find_one({'_id':ad.item._id})

            picture = picture_dao.find_one({"item.$id":ad.item._id, "order":"0"})
            
            picture_service = PictureService(ad.user.username, category.name, item._id)
            if picture is None:
                picture.fpath = picture_service.get_picture_path(None)
            else:
                picture.fpath = picture_service.get_picture_path(picture.fname)
            
            infos.append({'ad':ad, 'item':item, 'picture':picture})
        return infos